﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web.Mvc;
using Umbraco.Cms.Web.Context;
using Umbraco.Cms.Web.Model.BackOffice.PropertyEditors;
using Umbraco.Framework;
using Umbraco.Framework.Persistence.Model.Constants;
using Umbraco.Framework.Persistence.Model.Constants.Entities;
using Umbraco.Hive;
using Umbraco.Hive.RepositoryTypes;

namespace Umbraco.Cms.Web.PropertyEditors.UserPicker
{
	[PropertyEditor("B1B5C2B0-BD64-4488-8C0D-E72BB2EE6453", "UserPicker", "User Picker")]
	public class UserPickerEditor : PropertyEditor<UserPickerEditorModel, UserPickerPreValueModel>
	{
		private IUmbracoApplicationContext _appContext;

		public UserPickerEditor(IUmbracoApplicationContext appContext)
		{
			this._appContext = appContext;
		}

		public override UserPickerEditorModel CreateEditorModel(UserPickerPreValueModel preValueModel)
		{
			var model = new UserPickerEditorModel(preValueModel);

			var users = new List<SelectListItem>();
			users.Add(new SelectListItem { Text = "Choose...", Value = HiveId.Empty.ToString() });

			using (var uow = this._appContext.Hive.OpenReader<ISecurityStore>(new Uri("security://users")))
			{
				var items = uow.Repositories.GetEntityByRelationType<User>(FixedRelationTypes.ContentTreeRelationType, FixedHiveIds.UserVirtualRoot)
					.OrderBy(x => x.Name)
					.ToArray();

				foreach (var item in items)
				{
					users.Add(new SelectListItem() { Text = item.Name, Value = item.Id.ToString() });
				}
			}

			model.Users = users;

			return model;
		}

		public override UserPickerPreValueModel CreatePreValueEditorModel()
		{
			var model = new UserPickerPreValueModel();

			var userGroups = new List<SelectListItem>();

			using (var uow = this._appContext.Hive.OpenReader<ISecurityStore>(new Uri("security://user-groups")))
			{
				var items = uow.Repositories.GetEntityByRelationType<UserGroup>(FixedRelationTypes.ContentTreeRelationType, FixedHiveIds.UserGroupVirtualRoot)
					.OrderBy(x => x.Name)
					.ToArray();

				foreach (var item in items)
				{
					userGroups.Add(new SelectListItem() { Text = item.Name, Value = item.Id.ToString() });
				}
			}

			model.UserGroups = userGroups;

			return model;
		}
	}
}